﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EntityFrameworkETL.SaveBatchedChanges;

namespace EntityFrameworkETL
{
    public interface IBatchCommands
    {
        IEnumerable<BatchedCommand> BatchAndExecute(DbContext dbContext, IEnumerable<StructuredCommandCache> structuredCommandCaches
            , IExecuteBatchedCommand executeBatchedCommand
            , IFixupCommands fixupCommands);

    }
    public class BatchCommands : IBatchCommands
    {

        /// <summary>
        /// Batch commands staying within sql limit of 2100 parameters
        /// </summary>
        /// <param name="constructor"></param>
        /// <param name="commands"></param>
        public IEnumerable<BatchedCommand> BatchTable(IEnumerable<StructuredCommandCache> commands)
        {
            var result = new List<BatchedCommand>();
            var sql = new StringBuilder();
            var parameters = new List<DbParameter>();
            var batchedCommands = new List<StructuredCommandCache>();
            foreach (StructuredCommandCache command in commands)
            {
                if ((parameters.Count + command.CommandCache.DbCommand.Parameters.Count) > 2000)
                {
                    //BatchTable and clear
                    result.Add(new BatchedCommand(sql.ToString(), parameters.ToArray(), batchedCommands));
                    parameters.Clear();
                    sql.Clear();
                }

                var commandSql = command.CommandCache.DbCommand.CommandText;
                List<DbParameter> commandParameters = new List<DbParameter>();
                foreach (DbParameter param in command.CommandCache.DbCommand.Parameters)
                {
                    commandParameters.Add(param);
                }
                foreach (DbParameter param in commandParameters)
                {
                    //fix parameter names
                    var nextParameterName = "@p" + parameters.Count.ToString();
                    commandSql = commandSql.Replace("(" + param.ParameterName, "(" + nextParameterName);
                    commandSql = commandSql.Replace(param.ParameterName + ",", nextParameterName + ",");
                    commandSql = commandSql.Replace(param.ParameterName + ")", nextParameterName + ")");
                    param.ParameterName = nextParameterName;

                    parameters.Add(param);
                    command.CommandCache.DbCommand.Parameters.Remove(param);
                }
                sql.AppendLine(commandSql);
                batchedCommands.Add(command);
            }

            //BatchTable Batch Query
            result.Add(new BatchedCommand(sql.ToString(), parameters.ToArray(), batchedCommands));
            return result;
        }

        public IEnumerable<BatchedCommand> BatchAndExecute(DbContext dbContext, IEnumerable<StructuredCommandCache> structuredCommandCaches
            , IExecuteBatchedCommand executeBatchedCommand
            , IFixupCommands fixupCommands)
        {
            var result = new List<BatchedCommand>();
            var tableName = GetUnBatchedTableName(structuredCommandCaches);

            while (!string.IsNullOrWhiteSpace(tableName))
            {
                var tableCommands = GetCommandsForTableName(structuredCommandCaches, tableName);
                var batchedCommands = BatchTable(tableCommands);
                batchedCommands.ToList().ForEach(x => x.Commands.ToList().ForEach(y => y.CommandCache.HasBeenBatched = true));
                foreach (var batchedCommand in batchedCommands)
                {
                    var ids = executeBatchedCommand.Execute(dbContext, batchedCommand);
                    fixupCommands.Fixup(ids, batchedCommand);
                }
                
                result.AddRange(batchedCommands);

                tableName = GetUnBatchedTableName(structuredCommandCaches);
            }
            return result;
        }

        public static string GetUnBatchedTableName(IEnumerable<StructuredCommandCache> structuredCommandCaches)
        {
            foreach (var structuredCommandCache in structuredCommandCaches)
            {
                if (!structuredCommandCache.CommandCache.HasBeenBatched)
                    return structuredCommandCache.CommandCache.TableName;
            }
            //all tables have been executed at this level, look at children
            var children = structuredCommandCaches.SelectMany(x => x.ChildCommands);
            return children.Any() ? GetUnBatchedTableName(children) : null;

        }

        public static IEnumerable<StructuredCommandCache> GetCommandsForTableName(IEnumerable<StructuredCommandCache> structuredCommandCaches, string tableName)
        {
            var results = new List<StructuredCommandCache>();
            results.AddRange(structuredCommandCaches.Where(x => x.CommandCache.TableName == tableName));

            //all tables have been executed at this level, look at children
            var children = structuredCommandCaches.SelectMany(x => x.ChildCommands);
            if (children.Any())
                results.AddRange(GetCommandsForTableName(children, tableName));
            return results;
        }
    }
}
